package com.ext.aic.box;

import android.database.ContentObserver;
import android.os.Handler;
import android.provider.Settings;

import androidx.fragment.app.FragmentActivity;

import com.ext.aic.constants.EBusConstants;
import com.ext.aic.utils.PermissionUtils;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.ebus.SubscribeEBus;

public class AccessibilityObserver {
    private ContentObserver accessibilityObserver;
    private Handler handler = new Handler();
    private Runnable checkRunnable;
    private FragmentActivity activity;
    private IncreasingSeq delayTimeSeq = new IncreasingSeq(3000);

    private void setupAccessibilityObserver() {
        accessibilityObserver = new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange) {
                checkServiceStatus();
            }
        };
        activity.getContentResolver().registerContentObserver(
                Settings.Secure.getUriFor(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES),
                false,
                accessibilityObserver
        );
    }

    private void startPollingCheck() {
        checkRunnable = new Runnable() {
            @Override
            public void run() {
                checkServiceStatus();
                delayTimeSeq.increasing();
                handler.postDelayed(this, delayTimeSeq.getSequence());
            }
        };
        delayTimeSeq.reset();
        handler.post(checkRunnable);
    }

    private void checkServiceStatus() {
        if (!PermissionUtils.getInstance().isAccessibilityServiceEnabled(activity)) {
            handler.removeCallbacks(checkRunnable);
            AccessibilityManager.getInstance().setRunning(false);
        } else {
            AccessibilityManager.getInstance().setRunning(true);
            delayTimeSeq.reset();
        }
        //通知AI分身开关状态
        EBus.getInstance().post(EBusConstants.detectionAISeparateEnable);
    }

    public void destroy() {
        activity.getContentResolver().unregisterContentObserver(accessibilityObserver);
        handler.removeCallbacks(checkRunnable);
        delayTimeSeq.reset();
    }

    public void setup(FragmentActivity activity) {
        this.activity = activity;
        setupAccessibilityObserver();
        startPollingCheck();
        EBus.getInstance().registered(this);
    }

    @SubscribeEBus(receiveKey = EBusConstants.startedAccessibilityServer)
    public void onStartedAccessibilityService(boolean running) {
        delayTimeSeq.reset();
        if (!running) {
            AccessibilityManager.getInstance().setRunning(false);
        }
    }
}
